using Wlmy.Ids4.Common;
using IdentityServer4.EntityFramework.DbContexts;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Wlmy.Ids4.Model.CommonModel;

namespace Wlmy.Ids4.Repository
{
    public class UnitOfWork<T> : IUnitOfWork<T> where T : DbContext
    {
        private T _db = null;
        public T GetDbContext()
        {
            if (_db == null)
            {
                _db = StaticInfo.GetService<T>();
            }
            return _db;
        }

        public void SaveChanges()
        {
            if (_db != null)
            {
                BeforeSave();
                _db.SaveChanges();
            }
        }

        public async Task SaveChangesAsync()
        {
            if (_db != null)
            {
                BeforeSave();
                await _db.SaveChangesAsync();
            }
        }

        private void BeforeSave()
        {
            foreach (var entry in _db.ChangeTracker.Entries().ToList())
            {
                switch (entry.State)
                {
                    case EntityState.Added:
                        if (entry.Entity is Audit)
                        {
                            ((Audit)entry.Entity).CreationTime = DateTime.Now;
                        }
                        break;
                    case EntityState.Modified:
                        if (entry.Entity is Audit)
                        {
                            ((Audit)entry.Entity).LastModificationTime = DateTime.Now;
                        }
                        break;
                    case EntityState.Deleted:
                        if (entry.Entity is Audit)
                        {
                            var entity = (Audit)entry.Entity;
                            entity.IsDeleted = true;
                            entity.DeletionTime = DateTime.Now;
                            entry.State = EntityState.Modified;
                        }
                        break;
                }
            }
        }
    }
}
